package com.huahan.auth.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huahan.auth.Utils.CommonLoginUtils;
import com.huahan.auth.domain.UserInfo;
import com.huahan.auth.security.component.BusinessAuthenticationException;
import com.huahan.auth.service.UserInfoService;
import com.huahan.auth.mapper.UserInfoMapper;
import com.mall.common.constant.CommonConstant;
import com.mall.common.constant.LoginInfoParam;
import com.mall.common.constant.LoginTypeEnum;
import com.mall.common.constant.ResultCode;
import com.mall.common.utils.R;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
* @author 13513
* @description 针对表【t_user(用户信息表)】的数据库操作Service实现
* @createDate 2024-04-26 14:58:30
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{
    @Resource
    private CommonLoginUtils commonLoginUtils;
    @Override
    public R pwdLogin(LoginInfoParam loginInfoParam) {
        Map<String, String> params = new HashMap<>(16);
        // 密码方式登录
        params.put(CommonConstant.DEFAULT_PARAMETER_NAME_PHONE, loginInfoParam.getPhone());
        params.put(CommonConstant.DEFAULT_PARAMETER_NAME_PWD, loginInfoParam.getPassword());
        params.put("grant_type", LoginTypeEnum.PC_CODE.getValue());
        params.put("loginType", "password");
        params.put("flag", loginInfoParam.getFlag());//pc授权登录
        params.put("empType",loginInfoParam.getEmpType());// 是否安阳专区
        Map<String, Object> authInfo = commonLoginUtils.login(params);
        return R.okdata(authInfo);
    }

    @Override
    public UserInfo getAccountInfo() {
        Object principal = this.getPrincipal();
        if (!(principal instanceof UserInfo)) {
            throw new BusinessAuthenticationException(ResultCode.USER_FAIL);
        }
        UserInfo accountDTO = (UserInfo)principal;
        if (ObjectUtils.isEmpty(accountDTO)) {
            throw new BusinessAuthenticationException(ResultCode.USER_FAIL);
        }
        return accountDTO;
    }

    @Override
    public Object getPrincipal() {
        Authentication authentication = (Authentication) this.getAuthentication();
        if (!ObjectUtils.isEmpty(authentication)) {
            return authentication.getPrincipal();
        }
        return null;
    }

    /**
     * 获取登录信息
     *
     * @return Authentication
     */
    private Object getAuthentication() {
        SecurityContext context = SecurityContextHolder.getContext();
        return context.getAuthentication();
    }
}




